package com.example.farmeri.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.farmeri.R;
import com.example.farmeri.common.OnExtraClickListener;
import com.example.farmeri.data.config.ServiceConfig;
import com.example.farmeri.http.API;
import com.example.farmeri.data.RetrofitManager;
import com.example.farmeri.tools.ResponseUtils;
import com.example.farmeri.ui.users.model.UserList;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * Create by weiqishan on 2020/4/6.
 * 配置适配器
 */
public class UserManagerAdapter extends BaseRecycleViewAdapter{

    // 普通布局
    private final int TYPE_NORMAL = 1;
    // 脚布局
    private final int TYPE_FOOTER = 2;
    // 当前加载状态，默认为加载完成
    private int loadState = 1;
    // 正在加载
    public final int LOADING = 1;
    // 加载完成
    public final int LOADING_COMPLETE = 2;
    // 加载到底
    public final int LOADING_END = 3;

    private List<UserList.UserListBean> userList;

    Integer screeWidth;

    OnExtraClickListener onExtraClickListener;

    public UserManagerAdapter(Context context, int layout, int screeWidth) {
        super(context, layout);
        this.screeWidth = screeWidth;
        init();
    }

    public void init() {
        userList = new ArrayList();
        getUsers(1,999);
    }

    public void getUsers(int page,int limit){
        RetrofitManager.getManager().getRetrofit().create(API.class)
                .getAllUser(page,limit)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseUtils<UserList>>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseUtils<UserList> roleResponseUtils) {
                        if (roleResponseUtils.getCode() == 200){
                            UserList users = roleResponseUtils.getData();
                            users.getUserList().forEach(user -> {userList.add(user); });
                            notifyItemInserted(userList.size());
                        }else {
                            showMsg(roleResponseUtils.getMessage());
                        }

                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        showError();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        if(i == TYPE_NORMAL){
            View itemView = inflater.inflate(layout,viewGroup,false);
            return new MyViewHolder(itemView);
        }else if (i == TYPE_FOOTER){
            View itemView = inflater.inflate(R.layout.footer,viewGroup,false);
            return new FootViewHolder(itemView);
        }
        return null;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        if (viewHolder instanceof MyViewHolder){
            UserList.UserListBean user =  userList.get(viewHolder.getAdapterPosition());
            MyViewHolder myViewHolder = (MyViewHolder) viewHolder;
            if (!TextUtils.isEmpty(user.getIcon())){
                Glide
                    .with(context)
                    .load(ServiceConfig.getRootPath(user.getIcon()))
                    .into(myViewHolder.headImg);
            }
            myViewHolder.nickName.setText(user.getNick_name());
            myViewHolder.credit.setText(""+user.getCredit());
            myViewHolder.userType.setText("后台用户");
            myViewHolder.identity.setText(user.getIdentity());
            myViewHolder.layoutShow.setMinWidth(screeWidth);
            //设置滑动效果
            myViewHolder.container.setOnTouchListener((v, event) -> {
                //用户行为
                int action = event.getActionMasked();
                switch(action){
                    case MotionEvent.ACTION_UP:
                        //操作界面的宽度
                        int hideLayoutWidth = myViewHolder.layoutHide.getWidth();
                        //滑动的距离
                        int scrollX = myViewHolder.container.getScrollX();
                        //滑动距离大于操作界面的一半时显示操作界面
                        if (scrollX > hideLayoutWidth/2){
                            myViewHolder.container.smoothScrollTo(hideLayoutWidth,0);
                        }else {
                            myViewHolder.container.smoothScrollTo(0,0);
                        }
                        return true;
                }
                return false;
            });
            myViewHolder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                //获取当前的item位置
                int position = myViewHolder.getAdapterPosition();
                if (isChecked){
                    onExtraClickListener.onChecked(position);
                }else {
                    onExtraClickListener.onUnChecked(position);
                }

            });
            //设置点击界面勾选
            myViewHolder.layoutShow.setOnClickListener(v -> {
                if (myViewHolder.container.getScrollX() > 0){
                    myViewHolder.container.smoothScrollTo(0,0);
                    return;
                }
                myViewHolder.checkBox.setChecked(!myViewHolder.checkBox.isChecked());
            });
            //锁定
            myViewHolder.lock.setText(user.isLocked() ? "解锁" : "锁定");
            myViewHolder.lock.setOnClickListener(v -> {
                if (onExtraClickListener != null){
                    onExtraClickListener.onLockClick(v, user.getId());
                }

            });
            //点击编辑
            myViewHolder.edit.setOnClickListener(v -> {
                if (onExtraClickListener != null) {
                    onExtraClickListener.onEditClick(v,user.getId());
                }
            });
            //点击删除
            myViewHolder.del.setOnClickListener(v -> {
                if (onExtraClickListener != null) {
                    onExtraClickListener.onDelClick(v,user.getId());
                }
            });
        }else if(viewHolder instanceof FootViewHolder){
            FootViewHolder myViewHolder = (FootViewHolder)viewHolder;
            switch(loadState){
                case LOADING:
                    myViewHolder.container_loading.setVisibility(View.VISIBLE);
                    myViewHolder.container_complete.setVisibility(View.GONE);
                    break;
                case LOADING_COMPLETE: // 加载完成
                    myViewHolder.container_loading.setVisibility(View.GONE);
                    myViewHolder.container_complete.setVisibility(View.GONE);
                    break;

                case LOADING_END: // 加载到底
                    myViewHolder.container_loading.setVisibility(View.GONE);
                    myViewHolder.container_complete.setVisibility(View.VISIBLE);
                default:
                    break;
            }
        }

    }

    @Override
    public int getItemViewType(int position) {
        if (position < userList.size()){
            return TYPE_NORMAL;
        }
        return TYPE_FOOTER;
    }

    @Override
    public int getItemCount() {
        return userList.size()+1;
    }

    public void setOnExtraClickListener(OnExtraClickListener onExtraClickListener) {
        this.onExtraClickListener = onExtraClickListener;
    }

    public int getLoadState() {
        return loadState;
    }

    /**
     * 设置上拉加载状态
     *
     * @param loadState 0.正在加载 1.加载完成 2.加载到底
     */
    public void setLoadState(int loadState) {
        this.loadState = loadState;
        notifyDataSetChanged();
    }

    /**
     * 页脚  底部加载框
     */
    private class FootViewHolder extends RecyclerView.ViewHolder {
        ViewGroup container_loading;
        ViewGroup container_complete;

        FootViewHolder(View itemView) {
            super(itemView);
            container_loading = itemView.findViewById(R.id.footer_loading);
            container_complete = itemView.findViewById(R.id.footer_complete);
            container_loading.setVisibility(View.GONE);
            container_complete.setVisibility(View.GONE);
        }
    }

    private static class MyViewHolder extends RecyclerView.ViewHolder {

        HorizontalScrollView container; //显示界面与操作界面的容器
        ConstraintLayout layoutShow;    //显示界面
        LinearLayout layoutHide;    //操作界面
        CheckBox checkBox;    //复选框
        TextView lock;
        TextView del;
        TextView edit;
        TextView nickName;   //昵称
        TextView identity;   //昵称
        TextView userType;   //后台用户
        TextView credit;   //昵称
        ImageView headImg;   //头像


        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            container = itemView.findViewById(R.id.item_user_manager_container);
            layoutShow = itemView.findViewById(R.id.item_user_manager_layout_show);
            layoutHide = itemView.findViewById(R.id.item_user_manager_layout_hide);
            checkBox = itemView.findViewById(R.id.item_user_manager_checkBox);
            lock = itemView.findViewById(R.id.item_user_manager_lock);
            edit = itemView.findViewById(R.id.item_user_manager_edit);
            del = itemView.findViewById(R.id.item_user_manager_del);
            nickName = itemView.findViewById(R.id.item_user_manager_nickname);
            identity = itemView.findViewById(R.id.item_user_manager_identity);
            userType = itemView.findViewById(R.id.item_user_manager_user_type);
            credit = itemView.findViewById(R.id.item_user_manager_credit);
            headImg = itemView.findViewById(R.id.item_user_manager_img);
        }
    }
}